package com.sinopec.basemodule.utils;

import com.orhanobut.hawk.Hawk;
import com.sinopec.basemodule.AppConstants;
import com.sinopec.basemodule.BuildConfig;

import java.util.HashMap;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * WebServiceHelper 工具类
 */
public class WebServiceHelper {
    private static final OkHttpClient client = new OkHttpClient();
    private static String defaultUrl = "https://auth.uat.siam.sinopec.com/oauth/interface/";
    public static String baseurl = BuildConfig.isDebug ? Hawk.get(AppConstants.HAWK_APP_HOST, defaultUrl) : BuildConfig.OauthUrl;

    //应用标识 客户端应用注册 ID(base64)（POST）
    private static String client_id = "";
    //密钥 客户端应用注册密钥(base64)（POST）
    private static String client_secret = "";
    //认证类型 请求类型，默认（password）
    private static String grant_type = "password";

    /**
     * 发送GET请求
     *
     * @param url      请求的URL
     * @param callback 请求完成后的回调
     */
    public static void get(String url, Callback callback) {
        Request request = new Request.Builder()
                .url(baseurl + url)
                .build();
        client.newCall(request).enqueue(callback);
    }

    /**
     * 发送POST请求
     *
     * @param url      请求的URL
     * @param hashMap  请求的入参
     * @param callback 请求完成后的回调
     */
    public static void post(String url, HashMap<String, Object> hashMap, Callback callback) {
        hashMap.put("client_id", client_id);
        hashMap.put("client_secret", client_secret);
        hashMap.put("grant_type", grant_type);
        String jsonBody = GsonUtils.toJson(hashMap);
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(baseurl + url)
                .post(body)
                .build();
        client.newCall(request).enqueue(callback);
    }
}